<template>
    <div class="detail">
        <Header :title="pairsName" background-color="#FFFFFF" font-color="#000">
            <template #left>
                <van-icon name="arrow-left" size="25px" class="icon-left" @click="goBack()" />
            </template>
            <template #right>
                <van-icon :name="optional ? 'like' : 'like-o'" size="25px" color="#EA6149" class="icon-right"
                    @click="setOptinal(optional, id)" />
            </template>
        </Header>
        <div class="info">
            <div class="left">
                <div :class="['price', goodInfo.rate > 0 ? 'red' : 'green']">{{ goodInfo.close }}</div>
                <div :class="['increase', goodInfo.rate > 0 ? 'red' : 'green']">{{ (goodInfo.rate * 100).toFixed(3) }}%
                </div>
            </div>
            <div class="right">
                <div class="item">
                    <div class="key">{{ t('detail.high') }}</div>
                    <div class="value">{{ goodInfo.high }}</div>
                </div>
                <div class="item">
                    <div class="key">{{ t('detail.vol') }}</div>
                    <div class="value">{{ goodInfo.volume }}</div>
                </div>
                <div class="item">
                    <div class="key">{{ t('detail.low') }}</div>
                    <div class="value">{{ goodInfo.low }}</div>
                </div>
                <div class="item">
                    <div class="key">{{ t('detail.volum') }}</div>
                    <div class="value">{{ goodInfo.amount }}</div>
                </div>
            </div>
        </div>
        <nav>
            <div class="item" v-for="(item, index) in navList" :key="index" @click="selectInterval(item)">
                {{ item.name }}
            </div>
        </nav>
        <Kline ref="trade" @fromRandomCurrentPrice="fromRandomCurrentPrice" type="contract"></Kline>
        <main>
            <van-tabs v-model:active="active" swipeable>
                <van-tab v-for="(item, index) in [t('detail.secondContract'), t('detail.contract')]" :title="item"
                    :id="index">
                    <div class="btn" v-if="item == t('detail.secondContract')">
                        <div class="setDown green" @click="showDialog(1)">
                            {{ t('detail.buydecrease') }}
                        </div>
                        <div class="setUp red" @click="showDialog(2)">
                            {{ t('detail.buyincrease') }}
                        </div>
                    </div>
                    <div class="btn" v-if="item == t('detail.contract')">
                        <div class="setDown green" @click="showContractDialog(1)">
                            {{ t('detail.buydecrease') }}
                        </div>
                        <div class="setUp red" @click="showContractDialog(2)">
                            {{ t('detail.buyincrease') }}
                        </div>
                    </div>
                </van-tab>
            </van-tabs>
        </main>
        <Transition v-show="active == 0">
            <footer>
                <div class="history">
                    <div class="left">{{ t('detail.order-list') }}</div>
                    <div class="right" @click="goHistory()">{{ t('detail.history') }}<van-icon name="arrow" size="15px" />
                    </div>
                </div>
                <template v-if="list.length > 0">
                    <van-cell v-for="(item, index) in list" :key="item.id" @click="handleRecord(item.id)">
                        <div class="item">
                            <div class="items">
                                <span>{{ t('history.mc') }}</span>
                                <span>{{ item.pairsName }}</span>
                            </div>
                            <div class="items">
                                <span>{{ t('history.ksjg') }}</span>
                                <span>{{ item.startAmount }}</span>
                            </div>
                            <div class="items">
                                <span>{{ t('history.jgsj') }}</span>
                                <span>{{ secondsConfig[secondsConfig.findIndex(i => i.id == item.sid)].seconds }}{{
                                    secondsConfig[secondsConfig.findIndex(i => i.id == item.sid)].secondsTime }}</span>
                            </div>
                            <div class="items">
                                <span>{{ t('history.xzje') }}</span>
                                <span>{{ item.amount }}</span>
                            </div>
                            <div class="items">
                                <span>{{ t('history.mrzt') }}</span>
                                <span>
                                    <van-tag :type="item.buyStatus === 1 ? 'primary' : 'danger'">
                                        {{ item.buyStatus === 1 ? t('history.zhang') : t('history.die') }}
                                    </van-tag>
                                </span>
                            </div>
                            <div class="items" v-if="item.isWin !== 0">
                                <span>{{ t('history.sfsy') }}</span>
                                <span>
                                    <van-tag :type="item.isWin === 1 ? 'primary' : 'danger'">
                                        {{ item.isWin === 1 ? t('history.yin') : t('history.shu') }}
                                    </van-tag>

                                </span>
                            </div>
                            <div class="items">
                                <span>{{ t('history.gmsj') }}</span>
                                <span>{{ update(item.createTime) }}</span>
                            </div>
                            <div v-if="item.isWin !== 0" class="items">
                                <span>{{ t('history.ykje') }}</span>
                                <span :class="item.isWin === 1 ? 'fbcolor1' : 'fbcolor2'">
                                    {{ item.isWin === 1 ? '+' : '-' }}{{ item.profit }}
                                </span>
                            </div>
                        </div>
                    </van-cell>
                </template>
                <van-empty v-else image-size="100" description="描述文字" />
            </footer>
        </Transition>
        <Transition v-show="active == 1">
            <div class="contranctList">
                <div class="top flex-between bor_b">
                    <div class="tabBar c444">
                        <span :class="{ 'active': tabIndex == 0 }" @click="switchList(0)">
                            {{ t('detail.cc') }}
                            <i class="bottomLine"></i>
                        </span>
                        <span :class="{ 'active': tabIndex == 1 }" @click="switchList(1)">
                            {{ t('detail.ppwt') }}
                            <i class="bottomLine"></i>
                        </span>
                    </div>
                    <!-- <span class="all c999" @click="lookAll()">{{ t('detail.ckqb') }}</span> -->
                </div>

                <!-- 持仓列表 -->
                <div v-show="tabIndex == 0">
                    <!-- <div v-show="chicangList.length > 0" class="titleBox flex-between contract_style2 c666">
                        <span>{{ t('detail.cclb') }}</span>
                        <span class="blue_text" @click="yijianPingcang">{{ t('detail.yjpc') }}</span>
                    </div> -->
                    <div class="listBox" v-if="chicangList.length > 0">
                        <div v-for="(item, index) in chicangList" :key="index">
                            <ContractItem @res="handleResult" :list="item" :type="tabIndex == 0 ? '' : 'entrust'">
                            </ContractItem>
                        </div>
                    </div>
                    <!-- 空列表 -->
                    <Nodata :title="t('detail.zwcc')" v-else></Nodata>
                </div>


                <div v-show="tabIndex == 1">
                    <div class="listBox chicangList" v-if="wareList.length > 0">
                        <div v-for="(item, index) in wareList" :key="index">
                            <ContractItem @res="handleResult" :list="item" :type="tabIndex == 1 ? 'entrust' : ''">
                            </ContractItem>
                        </div>
                    </div>
                    <!-- 空列表 -->
                    <Nodata :title="t('detail.zwwt')" v-else></Nodata>
                </div>
            </div>
        </Transition>
        <!-- 秒合约 -->
        <Dialog v-model="show" :loading="isLoading" :confirm="t('confirm')" @onClose="onClose" @onConfirm="onConfirm"
            @onCancel="onCancel" :cancel="t('cancel')" :click-mask-is-close="false">
            <div class="dialog">
                <div class="title">
                    {{ t('detail.order') }}
                </div>
                <div class="time">
                    {{ t('detail.time') }}
                </div>
                <Grid v-model="curSecondsConfig" :list="secondsConfig" @onChange="onChange" />
                <div class="order-price">
                    {{ t('detail.order-price') }}:
                </div>
                <div class="stepper">
                    <div class="minus">
                        <van-icon name="minus" @click="modfiyValue('minus')" />
                    </div>
                    <input @input="inputChange" v-model="secondForm.amount" type="text" class="input">
                    <div class="plus">
                        <van-icon name="plus" @click="modfiyValue('plus')" />
                    </div>
                </div>
                <div class="all-price" @click="setAllMoney">
                    {{ t('detail.all-price') }}
                </div>
                <div class="decription">
                    <div class="rows">
                        <div class="item">
                            <div class="key">{{ t('detail.direction') }}:</div>
                            <div class="value">{{ secondForm.buyStatus == 2 ? t('detail.buyincrease') :
                                t('detail.buydecrease') }}</div>
                        </div>
                        <div class="item">
                            <div class="key">{{ t('detail.preview-price') }}:</div>
                            <div class="value">{{ previewBalance }}%</div>
                        </div>
                    </div>
                    <div class="colums">
                        <div class="item">
                            <div class="key">{{ t('detail.current-price') }}</div>
                            <div class="value">{{ goodInfo.close }}</div>
                        </div>
                        <div class="item">
                            <div class="key">{{ t('detail.current-balance') }}</div>
                            <div class="value">{{ userInfo.amt }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </Dialog>
        <!-- 合约 -->
        <Dialog v-model="contractShow" :loading="isContractLoading" :confirm="t('confirm')" @onClose="onContractClose"
            @onConfirm="onContractConfirm" @onCancel="onContractCancel" :cancel="t('cancel')">
            <div class="leftBox">
                <!-- <div class="btnBox">
                    <span :class="['btn', 'btn1', { cur: operationType == 'open' }]" @click="operation('open')">
                        {{ t('detail.kc') }}
                        <img src="../../../../assets/detail/green_bg.png" srcset alt v-if="operationType == 'open'">
                    </span>
                    <span :class="['btn', { cur: operationType == 'close' }]" @click="operation('close')">
                        {{ t('detail.pc') }}
                        <img src="../../../../assets/detail/orange_bg.png" srcset alt v-if="operationType == 'close'">
                    </span>
                </div> -->
                <div class="entrustsBox">
                    <div class="entrusts flex">
                        <div class="items" @click="priceShow = true">
                            <span v-show="contractForm.orderType == '1'" class="size12 c222">
                                {{ t('detail.sj') }}
                            </span>
                            <span v-show="contractForm.orderType == '2'" class="size12 c222">
                                {{ t('detail.xianjia') }}
                            </span>
                            <img src="../../../../assets/detail/dropDown.png" alt srcset class="icons">
                        </div>
                        <!-- 市价 限价 选择弹出层 -->
                        <div class="ganggan c333" v-show="priceShow">
                            <div class="con">
                                <van-picker show-toolbar :title="t('detail.xzlx')" :columns="actions" :option-height="50"
                                    @cancel="priceShow = false" @confirm="selectPrice" :confirm-button-text="t('confirm')"
                                    :cancel-button-text="t('cancel')"></van-picker>
                            </div>
                        </div>
                        <!-- 杠杆 -->
                        <div class="items" @click="gangganShow = true" v-if="operationType == 'open'">
                            <span class="size12 c222">{{ t('detail.gg') }}</span>
                            <span class="size10 blue_text">{{ contractForm.leverNum }}X</span>
                            <img src="../../../../assets/detail/dropDown.png" alt srcset class="icons">
                        </div>
                        <div class="items" v-else>
                            <span class="size12 c222">{{ t('detail.gg') }}</span>
                            <span class="size10 c999">{{ contractForm.leverNum }}X</span>
                            <img src="../../../../assets/detail/dropDown.png" alt srcset class="icons">
                        </div>
                        <!-- 杠杆 选择弹出层 -->
                        <div v-show="gangganShow" class="ganggan c333">
                            <div class="con">
                                <van-picker show-toolbar :title="t('detail.xzgg')" :confirm-button-text="t('confirm')"
                                    :cancel-button-text="t('cancel')" :columns="columns" :option-height="50"
                                    @cancel="gangganShow = false" @confirm="selGangganOk"></van-picker>
                            </div>
                        </div>
                        <van-overlay :show="gangganShow" @click="gangganShow = false"></van-overlay>
                        <van-overlay :show="priceShow" @click="priceShow = false"></van-overlay>
                    </div>
                    <!-- 市价 -->
                    <div v-show="contractForm.orderType == 1" class="entrusts entrusts1 pad_l_10">
                        <span class="name">{{ t('detail.sj') }}</span>
                        <span class="rightBorder" @click="contractForm.orderType = 2">{{ t('detail.sj') }}</span>
                    </div>
                    <!-- 限价 -->
                    <div v-show="contractForm.orderType == 2" class="entrusts entrusts1" style="padding-left: 0;">
                        <div class="name a_re" style="width:100%;height:100%">
                            <input ref="input1" class="inp c666" type="number" :placeholder="t('detail.jg')"
                                v-model="contractForm.price">
                            <div class="a_ab c666 right5 top5 size12">
                                {{ '' }}
                            </div>
                        </div>
                        <span class="rightBorder2 c111" @click="contractForm.orderType = 1">{{ t('detail.xianjia') }}</span>
                    </div>
                    <div class="entrusts a_re">
                        <!-- 开仓手数输入 -->
                        <input ref="input2" v-show="operationType == 'open'"
                            :class="['inppp', 'c666', { bg_ededed: disabled }]" type="number" :disabled="disabled"
                            v-model="contractForm.buyNum" @input="changeShoushu(contractForm.buyNum)"
                            :placeholder="t('detail.sl')">
                        <!-- 平仓手数输入 -->
                        <input ref="input3" v-show="operationType == 'close'"
                            :class="['inppp', 'c666', { bg_ededed: disabledPingcang }]" type="number"
                            :disabled="disabledPingcang" v-model="shouNumPing" @input="changeShoushu(shouNumPing)"
                            :placeholder="t('detail.sl')">
                        <span class="a_ab right10 top5 c111">{{ t('detail.s') }}</span>
                    </div>
                </div>
                <div v-if="operationType == 'open'" class="size11 c777 mar_t_5 bold">
                    = {{ (contractConfig.contractPrice * handerNan(contractForm.buyNum)).toFixed(4) }}{{ pairsName }}
                </div>
                <div v-else class="hei20"></div>

                <!-- 开仓进度条 -->
                <div class="pad_l_r_10" v-show="operationType == 'open'">
                    <van-slider :disabled="disabled" v-model="sliderNum" @update:model-value="changeSlide(sliderNum)"
                        active-color="#38BB96" class="mar_t_20">
                        <img src="../../../../assets/detail/icon1.png" slot="button" class="handleBtn">
                    </van-slider>
                </div>
                <!-- 开仓进度条 右侧百分百 -->
                <div v-show="operationType == 'open'" class="amountBox flex-between c999 size10 mar_t_10">
                    <span>0%</span>
                    <span>{{ handerNan(sliderNum) }}%</span>
                </div>

                <!-- 平仓进度条 -->
                <!-- <div class="pad_l_r_10" v-show="operationType == 'close'">
                    <van-slider :disabled="disabledPingcang" v-model="sliderNumPing" @input="changeSlidePing(sliderNumPing)"
                        active-color="#38BB96" class="mar_t_20">
                        <img src="../../assets/images/home/icon1.png" slot="button" class="handleBtn" />
                    </van-slider>
                </div> -->
                <!-- 平仓进度条 右侧百分百 -->
                <!-- <div v-show="operationType == 'close'" class="amountBox flex-between c999 size10 mar_t_10">
                    <span>0%</span>
                    <span>{{ handerNan(sliderNumPing) }}%</span>
                </div> -->

                <!-- 止盈止损 -->
                <div class="entrustsBox" style="margin-bottom: 10px;">
                    <div class="entrusts entrusts1" style="padding-left: 0;">
                        <div class="name a_re" style="width:100%;height:100%">
                            <input class="inp c666" type="number" v-model="contractForm.stopProfit"
                                @input="changeStopProfit(contractForm.stopProfit)" :placeholder="t('detail.profit')">
                            <div class="a_ab c666 right5 top5 size12">{{ '' }}</div>
                        </div>
                        <span class="rightBorder3 size12 c111">{{ t('detail.profit').slice(0, 2) }}</span>
                    </div>
                    <div class="entrusts entrusts1" style="padding-left: 0;">
                        <div class="name a_re" style="width:100%;height:100%">
                            <input class="inp c666" type="number" v-model="contractForm.stopLoss"
                                @input="changeStopLoss(contractForm.stopProfit)" :placeholder="t('detail.loss')">
                            <div class="a_ab c666 right5 top5 size12">{{ '' }}</div>
                        </div>
                        <span class="rightBorder4 size12 c111">{{ t('detail.loss').slice(0, 2) }}</span>
                    </div>
                </div>
                <!-- 资产 -->
                <div class="balanceBox c222" style="margin-bottom: 10px;">
                    <div class="items">
                        <span>{{ t('detail.kyzc') }}</span>
                        <span>{{ keyongzican }}</span>
                    </div>
                    <div class="items" v-if="operationType == 'open'">
                        <span>{{ t('detail.kkss') }}</span>
                        <span>&lt;&nbsp;{{ kekaishoushu }}</span>
                    </div>
                    <div class="items">
                        <span>{{ t('detail.dqzc') }}</span>
                        <span>{{ userInfo.amt }}</span>
                    </div>
                    <div class="items">
                        <!-- 保证金=手数×合约乘数×下单价格/杠杆 -->
                        <span>{{ t('detail.bzj') }}</span>
                        <span>{{ baozhengjin }}</span>
                    </div>
                </div>
            </div>
        </Dialog>
        <van-dialog @confirm="onDiaConfirm" v-model:show="isShowYiJian"
            :title="curType == 'MATCH' ? t('detail.pc') : t('detail.chedan')" show-cancel-button>
            <div style="text-align: center; padding: 20px 0px;">
                {{ curType == 'MATCH' ? ('detail.yjpc') : t('detail.sfcg') }}
            </div>
        </van-dialog>
        <HyTime :currentPrice="goodInfo.close" :diffTime="diffTime" :show-pup="showTime" :currentDta="hyDetails"
            @updateShowPup="updateShowPup" :currentRate="currentRate"></HyTime>
        <HyFinish :show-pup="showFinsh" :currentDta="hyDetails" @updateFinShowPup="updateFinShowPup"></HyFinish>
    </div>
</template>

<script setup>
import Header from "@/components/Header/index.vue";
import Dialog from "@/components/Dialog/index.vue";
import Grid from "@/components/Grid/index.vue";
import Kline from "@/components/Kline/index.vue";
import HyFinish from "@/components/HyFinish/index.vue";
import HyTime from "@/components/HyTime/index.vue";
import Nodata from "@/components/Nodata/index.vue";
// import ContractItem from "@/components/ContractItem/index.vue";
import useLanguage from '@/hooks/useLanguage';
import { marketApi, userApi } from '@/api'
import { reactive, watch, computed, ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { showNotify } from 'vant';
import { storeToRefs } from 'pinia'
import { UserStore } from '@/store/user';
import { useRouter } from 'vue-router'
const router = useRouter()

const { t } = useLanguage()
const userStore = UserStore()
const { userInfo, cateId } = storeToRefs(userStore)


const props = defineProps(['pairsName', 'id'])
const navList = ref([
    {
        name: "分时",
        type: "1",
        chartType: 3
    },
    {
        name: "5分",
        type: "5",
        chartType: 1
    },
    {
        name: "15分",
        type: "15",
        chartType: 1
    },
    {
        name: "30分",
        type: "30",
        chartType: 1
    },
    {
        name: "1小时",
        type: "60",
        chartType: 1
    },
    {
        name: "1天",
        type: "D",
        chartType: 1
    }
])

function selectInterval(item) {
    trade.value.setTime(item.type)
}
function fromRandomCurrentPrice(params) {
    const { higPrice, lowPrice, volume, volume24, rate, close } = params
    goodInfo.high = higPrice
    goodInfo.low = lowPrice
    goodInfo.volume = volume24
    goodInfo.close = close
    goodInfo.rate = rate
}
// 获取价格
const goodInfo = reactive({
    close: 0,
    high: 0,
    low: 0,
    open: 0,
    rate: 0,
    symbol: "",
    volume: 0,
    amount: 0,
})
async function getPriceByName() {
    const postData = { pairsName: props.pairsName }
    const { code, data } = await marketApi.getPriceByName(postData)
    if (code === 20000) {
        Object.assign(goodInfo, data)
    }
}
// 获取自选信息
const optional = ref(false)
const isOptional = async () => {
    const postData = { pairsName: props.pairsName }
    const { code, data } = await userApi.isOptional(postData)
    if (code == 20000) {
        optional.value = data
    }
}
async function setOptinal(params, id) {
    if (params) {
        // true 删除自选
        const postData = { id }
        const { code, data } = await userApi.delOptionalById(postData)
        if (code == 20000) {
            isOptional()
        }
    } else {
        // false 添加自选
        const postData = { pairsName: props.pairsName, pairsId: id }
        const { code, data } = await userApi.addOptional(postData)
        if (code == 20000) {
            isOptional()
        }
    }
}
// 秒合约配置
async function getSecondsConfig() {
    const { code, data } = await marketApi.getSecondsConfig()
    if (code === 20000) {
        return data
    }
}



// 对话框
const active = ref(0)
const secondsConfig = ref([])
const curSecondsConfig = ref(0)
const previewBalance = ref(0)

function onChange(index) {
    secondForm.sid = secondsConfig.value[index].id
    previewBalance.value = secondsConfig.value[index].odds
    secondForm.amount = secondsConfig.value[index].minAmt
    inputChange()
}
function inputChange() {
    if (/^[0-9]+(.[0-9]{2})?$/.test(secondForm.amount)) {
        if (secondForm.amount <= userInfo.value.amt) {
            // 判断是否大于最小交易额 可以交易修改

        } else {
            secondForm.amount = 0.00
        }
    } else {
        secondForm.amount = Number(secondsConfig.value[curSecondsConfig.value].minTrade).toFixed(2)
        if (/^[0-9]+(.[0-9]{2})?$/.test(secondForm.amount)) {
            if (secondForm.amount <= userInfo.value.amt) {
                // 判断是否大于最小交易额 可以交易修改

            } else {
                secondForm.amount = 0.00
            }
        }
    }
}

function modfiyValue(type) {
    if (type == 'minus') {
        // 减 
        secondForm.amount = Number(Number(secondForm.amount) - 100).toFixed(2)

    } else {
        // 加
        secondForm.amount = Number(Number(secondForm.amount) + 100).toFixed(2)

    }
    if (/^[0-9]+(.[0-9]{2})?$/.test(secondForm.amount)) {
        if (secondForm.amount <= userInfo.value.amt) {
            // 判断是否大于最小交易额 可以交易修改

        } else {
            secondForm.amount = 0.00
        }
    } else {
        secondForm.amount = Number(secondsConfig.value[curSecondsConfig.value].minTrade).toFixed(2)
        if (/^[0-9]+(.[0-9]{2})?$/.test(secondForm.amount)) {
            if (secondForm.amount <= userInfo.value.amt) {
                // 判断是否大于最小交易额 可以交易修改

            } else {
                secondForm.amount = 0.00
            }
        }
    }
}
function setAllMoney() {
    secondForm.amount = userInfo.value.amt
}
const show = ref(false)
const showDialog = (type) => {
    new Promise(async (resolve, reject) => {
        const data = await getSecondsConfig()
        resolve(data)
    }).then(res => {
        secondsConfig.value = res
        secondForm.startAmount = goodInfo.close
        secondForm.sid = secondsConfig.value[curSecondsConfig.value].id // 初始化默认值
        secondForm.buyStatus = type
        previewBalance.value = secondsConfig.value[curSecondsConfig.value].odds
        secondForm.amount = Number(secondsConfig.value[curSecondsConfig.value].minTrade).toFixed(2)
        if (/^[0-9]+(.[0-9]{2})?$/.test(secondForm.amount)) {
            if (secondForm.amount <= userInfo.value.amt) {
                // 判断是否大于最小交易额 可以交易修改

            } else {
                secondForm.amount = 0.00
            }
        }

        show.value = true
    })
}

const secondForm = reactive({
    sid: '',
    pairsName: props.pairsName,
    cateId: cateId.value,
    startAmount: '',
    amount: '',
    buyStatus: ''
})
function onClose() {

}
function onCancel() {
}

const isclick = ref(true)
const isLoading = ref(false)
async function onConfirm() {
    //  延时3秒点击
    if (isclick.value) {
        isclick.value = false
        isLoading.value = true
        const res = await marketApi.addSeconds(secondForm)
        if (res.code === 20000) {
            if (res.success) {
                const { data } = res
                showNotify({ message: t('detail.addSeconds'), type: 'success' })
                await handleRecord(data.id)
                showTime.value = true
            } else {
                showNotify({ message: t('detail.minusSeconds'), type: 'danger' })
            }
            isLoading.value = false
            getTradeListNoSettle()
        }

        setTimeout(() => {
            isLoading.value = false
            isclick.value = true
        }, 3000)
    }
}

// 查询单个秒合约记录
const newTimer = ref(null)
const diffTime = ref(null)
const currentRate = ref(null)
const secondId = ref(null)
const hyDetails = reactive({})
const showFinsh = ref(false)
const showTime = ref(false)
async function handleRecord(id) {
    const postDataSecond = {
        id
    }
    if (newTimer.value != null) {
        clearInterval(newTimer.value)
    }
    diffTime.value = 0
    currentRate.value = 0
    secondId.value = id
    const { code, data } = await marketApi.getSecondsById(postDataSecond)
    if (code == 20000) {
        Object.assign(hyDetails, data)
        if (data.secondsConfig) {
            const secondsTime = data.secondsConfig.seconds
            currentRate.value = secondsTime
            diffTime.value = data.timing
            currentRate.value = currentRate.value > 0 ? currentRate.value : 0
            if (diffTime.value < 1) {
                showFinsh.value = true
            } else {
                showTime.value = true
                Time()
            }
        }

    }
}

function Time() {
    newTimer.value = setInterval(() => {
        diffTime.value -= 1
        if (diffTime.value > 0) {

        } else {
            if (newTimer.value != null) {
                clearInterval(newTimer.value)
            }
            setTimeout(() => {
                // 关闭弹窗
                showTime.value = false
                handleRecord(secondId.value)
            }, 3000)
        }
    }, 1000)
}

function updateShowPup(id) {
    showTime.value = false
    getTradeListNoSettle()
    if (diffTime.value < 1) {
        handleRecord(id)
    }
}
function updateFinShowPup() {
    showFinsh.value = false
    getTradeListNoSettle()
}




// 合约下单
const operationType = ref('open')
const currentTypeOpen = ref(true)
function operation(type) {
    if (type == operationType.value) {
        return
    }
    operationType.value = type
    if (type == 'close') {
        currentTypeOpen.value = false
        // 平仓
        disabled.value = false
    } else {
        // 开仓
        currentTypeOpen.value = true
        disabled.value = false

    }
    sliderNum.value = 0

}

// 市价 限价
const priceShow = ref(false)
const actions = ref([{
    text: t('detail.sj'),
    value: 1,
}, {
    text: t('detail.xianjia'),
    value: 2,
}])
// 市价 限价 选择弹出层
function selectPrice(e) {
    contractForm.orderType = e.selectedOptions[0].value
    priceShow.value = false
}

// 杠杆
const gangganShow = ref(false)
const columns = ref([])
function selGangganOk(e) {
    contractForm.leverNum = e.selectedOptions[0].value
    gangganShow.value = false
    // 选择了杠杆，那么手数和 进度条 初始化

}

// 杠杆配置
const gangganSet = ref([])
async function getGangganList() {
    const { code, data } = await marketApi.getLeverList()
    if (code == 20000 && data) {
        gangganSet.value = data
        columns.value = data.map(item => {
            return {
                text: `${item.lever}X`,
                value: item.lever
            }
        })
        const item = data.find(item => item.lever == 100)
        return item
    }
}

// 获取合约配置
const contractConfig = reactive({
    id: '',
    openFeeRate: '',
    closeFeeRate: '',
    stopRate: '',
    maxBuyRate: '',
    contractPrice: '',
    updateTime: '',
})
async function getContractConfig() {
    const { code, data } = await marketApi.getContractConfig()
    if (code == 20000 && data) {
        return data
    }
}

// currentPriceType == 1 ， 2
const input1 = ref(null)

// input2
const disabled = ref(false) // input2 开仓
const sliderNum = ref(0) // input2 开仓
// input3
const shouNumPing = ref('') // input3 平仓
const disabledPingcang = ref(false) // input3 平仓

// 可用资产
const keyongzican = computed(() => {
    const amt = userInfo.value.amt
    const maxBuyRate = contractConfig.maxBuyRate
    return Math.floor(amt * maxBuyRate)
})

// 可开手数
const kekaishoushu = computed(() => {
    const amt = userInfo.value.amt
    const maxBuyRate = contractConfig.maxBuyRate
    const contractPrice = contractConfig.contractPrice
    const leverNum = contractForm.leverNum
    return Math.floor(((amt * maxBuyRate) * leverNum) / (contractPrice * goodInfo.close))
})

// 保证金
const baozhengjin = computed(() => {
    const buyNum = contractForm.buyNum == '' ? 0 : contractForm.buyNum
    const contractPrice = contractConfig.contractPrice
    const price = contractForm.price == '' ? 0 : contractForm.price
    const leverNum = contractForm.leverNum == '' ? 0 : contractForm.leverNum
    return Math.floor(buyNum * contractPrice * price / leverNum)
})
function changeShoushu(val) {
    if (val > kekaishoushu.value) {
        sliderNum.value = 100
        contractForm.buyNum = kekaishoushu.value
    } else {
        contractForm.buyNum = parseInt(val)
        const v = (contractForm.buyNum / kekaishoushu.value) * 100
        sliderNum.value = v.toFixed(2) - 0
    }
}

// 判断是否是Number类型， 是则返回本值，否则返回0
function handerNan(n) {
    if (isNaN(n)) {
        return 0;
    } else {
        return n;
    }
}
// 开仓 步进条
function changeSlide(val) {
    const shounum = (val / 100) * kekaishoushu.value
    contractForm.buyNum = parseInt(shounum)
}

// 止盈止损
function changeStopProfit(val) {
    if (val < 0) {
        contractForm.stopProfit = 0
    }
}

function changeStopLoss(val) {
    if (val < 0) {
        contractForm.stopProfit = 0
    }
}

// 对话框
const isContractLoading = ref(false)
const contractShow = ref(false)
const contractForm = reactive({
    pairsName: props.pairsName,
    leverNum: 100,
    contractPrice: '',
    price: '',
    buyNum: '',
    buyType: '',
    orderType: 1,
    stopProfit: 1000,
    stopLoss: 1000,
})
// 监听市价限价
watch(() => contractForm.orderType, (n, o) => {
    if (n == 2) {
        contractForm.price = Number(goodInfo.close).toFixed(4) - 0
    } else if (n == 1) {
        contractForm.price = Number(goodInfo.close)
    }
})
// 进度条
watch(sliderNum, (n, o) => {
    if (contractForm.price == '' && contractForm.orderType == 2) {
        showNotify({
            message: t('detail.toast'),
            type: 'warning',
        })
        sliderNum.value = 0
    }
})
function showContractDialog(type) {
    new Promise(async (resolve, reject) => {
        contractForm.buyType = type
        contractForm.price = goodInfo.close
        const promises = [getGangganList(), getContractConfig()]
        for await (const item of promises) {
            if (item.lever) {
                resolve(item)
                contractForm.leverNum = item.lever
            } else {
                Object.assign(contractConfig, item)
                contractForm.contractPrice = contractConfig.contractPrice
            }
        }
    }).then(res => {
        contractShow.value = true
    })
}


function onContractClose() {
    // console.log(contractForm);
}

const isContractClick = ref(true)
const isAddContractLoading = ref(false)
async function onContractConfirm() {
    if (isContractClick.value) {
        isContractClick.value = false
        isAddContractLoading.value = true
        const { code, data, success } = await marketApi.buyContract(contractForm)
        if (code == 20000 && success) {
            showNotify({ message: t('detail.addSeconds'), type: 'success' })
        } else {
            showNotify({ message: t('detail.minusSeconds'), type: 'danger' })
        }
        isAddContractLoading.value = false
        getContractNoFinish()
        chicangList.value = []
        getPositionList()

        setTimeout(() => {
            isAddContractLoading.value = false
            isContractClick.value = true
        }, 3000)
    }
}
function onContractCancel() {

}


// 历史交易
const tabIndex = ref(0)
const wareGetData = reactive({
    pageNum: 1,
    pageSize: 10,
})
const wareList = ref([]) // 委托列表
const chicangGetData = reactive({
    pageNum: 1,
    pageSize: 10,
})
const chicangList = ref([]) // 持仓列表
const pages = ref()
const isNoList = ref(false)
// 获取委托列表
async function getContractNoFinish() {
    const { code, data } = await marketApi.getContractNoFinish(wareGetData)
    if (code == 20000) {
        const { records } = data
        wareList.value = records
        console.log(wareList.value, { name: 'getContractNoFinish' });
    }

}
// 获取持仓列表
async function getPositionList() {
    const { code, data } = await marketApi.getPositionList(chicangGetData)
    if (code == 20000) {
        const { records } = data
        pages.value = data.pages
        if (records && records.length > 0) {
            records.map(item => chicangList.value.push(item))
        } else {
            isNoList.value = true
        }
        console.log(chicangList.value, { name: 'getPositionList' });
    }
}

// 处理合约交易
function handleContractRecord(id) {

}

function switchList(num) {
    if (num == tabIndex.value) {
        return
    }
    tabIndex.value = num
}

// 查看全部
function lookAll() {

}

// 一键平仓
function yijianPingcang() {

}
const isShowYiJian = ref(false)
const curItem = reactive({})
const curType = ref('MATCH')
// 底部数据 子组件传来的平仓数据
function handleResult(data, type, price) {
    Object.assign(curItem, data)
    curType.value = price
    isShowYiJian.value = true
}

function onDiaConfirm() {
    if (curType.value == 'MATCH') {
        pingcang()
    } else {
        chedan()
    }
    isShowYiJian.value = false
    chicangList.value = []
    getPositionList()
    getContractNoFinish()
    
}

async function pingcang() {
    const res = await marketApi.sellUserPosition({ id: curItem.id })
    if (res.code == 20000) {
        showNotify({
            message: t('detail.pccg'),
            type: 'success'
        })
    }
}
async function chedan() {
    const res = await marketApi.revokeContract({ id: curItem.id })
    if (res.code == 20000) {
        showNotify({
            message: t('detail.cdcg'),
            type: 'success'
        })
    }
}






// history
const list = ref([]);
const loading = ref(false)
const postData = reactive({
    pageNum: 1,
    pageSize: 10
})
async function getTradeListNoSettle() {
    const { code, data } = await userApi.getTradeListNoSettle(postData)
    if (code == 20000) {
        if (data && data.records) {
            list.value = [...data.records]
        }
        loading.value = false
    }
}

function goHistory() {
    router.push({ name: 'history' })
}

function goBack() {
    router.go(-1)
}

const update = (date) => {
    const time = new Date(date).getTime()
    const second = new Date(date).getSeconds()
    const minute = new Date(date).getMinutes()
    const hour = new Date(date).getHours()
    const curdate = new Date(date).getDate()
    const mounth = new Date(date).getMonth() + 1
    const year = new Date(date).getFullYear()



    const newDate = `${year} ${mounth < 10 ? '0' + mounth : mounth}-${curdate < 10 ? '0' + curdate : curdate} ${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}:${second < 10 ? '0' + second : second}`
    return newDate
}

function handleScroll(e) {
    const scrollTop = document.scrollingElement.scrollTop // 滚动条的位置
    const windowHeitht = document.scrollingElement.clientHeight // 在页面上返回内容的可视高度
    const scrollHeight = document.scrollingElement.scrollHeight // 返回整个元素的高度（包括带滚动条的隐蔽的地方）
    // 是否滚动到底部的判断
    if ((Math.round(scrollTop) + windowHeitht) == scrollHeight) {
        // console.log('到底部了');
        if (chicangGetData.pageNum < pages.value) {
            chicangGetData.pageNum++
            getPositionList()
            isNoList.value = false
        } else {
            isNoList.value = true
        }
    }
}

const trade = ref(null)
onMounted(async () => {
    isOptional()
    getPriceByName()
    secondsConfig.value = await getSecondsConfig()
    getTradeListNoSettle()
    getContractNoFinish()
    getPositionList()
    nextTick(() => {
        trade.value.tradingViewInit(props.pairsName, navList.value[0].type)
        document.addEventListener('scroll', handleScroll)
    })
})
onBeforeUnmount(() => {
    document.removeEventListener('scroll', handleScroll)
})
</script>

<style lang="less" scoped>
.detail {
    height: 100vh;
}

.icon-left {
    margin-left: 10px;
}

.icon-right {
    margin-right: 10px;
}

.info {
    height: 150px;
    width: 100%;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 10px;

    .left {
        width: 50%;
        display: flex;
        flex-direction: column;

        .increase {
            font-size: 20px;
            font-weight: 100;
            color: #333;
            margin-left: 10px;
        }

        .price {
            font-size: 28px;
            font-weight: 200;
            color: #333;
            margin-left: 10px;
        }

        .red {
            color: #FD614E;
        }

        .green {
            color: #60AE68;
        }
    }

    .right {
        width: 50%;
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        grid-template-rows: repeat(2, minmax(0, 1fr));
        column-gap: 16px;
        row-gap: 8px;

        .item {
            font-weight: 500;
            font-size: 14px;
            text-align: center;

            .key {}

            .value {}
        }
    }
}

nav {
    display: grid;
    grid-template-columns: repeat(6, minmax(0, 1fr));
    text-align: center;
    background-color: #fff;
    margin-bottom: 5px;

    .item {
        color: #2196F3;
        font-size: 15px;
        height: 30px;
        line-height: 30px;
        padding: auto;

        &:active {
            transition: all 0.5s;
            background-color: #E4F2FE;
        }
    }
}

.chart {
    height: 415px;
    width: 100%;
    background-color: #fff;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    box-sizing: border-box;
}

main {
    width: 100%;


    .btn {
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 65px 0px;

        div {
            width: 130px;
            height: 60px;
            border-radius: 5px;
            line-height: 60px;
            text-align: center;
        }

        div~div {
            margin-left: 20px;
        }

        .green {
            background-color: #60AE68;
            transition: all .3s;

            &:active {
                background-color: #24642a;
            }
        }

        .red {
            background-color: #FD614E;
            transition: all .3s;

            &:active {
                background-color: #77271c;
            }
        }
    }
}

footer {
    padding-top: 10px;

    .history {
        display: flex;
        justify-content: space-between;
        padding: 13px;
        box-sizing: border-box;
        color: rgba(0, 0, 0, 0.5);
    }

    .item {
        overflow: hidden;
        background-color: #FFFFFF;
        box-sizing: border-box;
        padding: 11px;
        margin-bottom: 15px;
        border-radius: 5px;
        border: solid 1px rgba(0, 0, 0, 0.1);
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

        .items {
            margin-top: 5px;
            font-size: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }
    }
}

.dialog {
    .title {
        font-size: 24px;
        font-weight: 600;
        margin: 10px 0px 15px;
        text-align: center;
    }

    .time {
        text-align: center;
        font-size: 20px;
        font-weight: 500;
    }


    .order-price {
        text-align: center;
        margin: 10px 0px;
        font-size: 20px;
    }

    .stepper {
        display: flex;
        align-items: center;
        border: 1px solid #ccc;
        height: 50px;
        padding: 0px 10px;
        box-sizing: border-box;

        .input {
            border: none;
            outline: none;
            text-align: center;
        }
    }

    .all-price {
        color: #fff;
        text-align: center;
        background-color: #1690F8;
        width: 130px;
        height: 50px;
        line-height: 50px;
        border-radius: 5px;
        box-shadow: 0px 2px 3px #73ABD7;
        margin: 10px auto 0px;
        transition: all .25s;
    }

    .all-price:active {
        background-color: #0a76d4;
    }

    .decription {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-bottom: 40px;

        .rows {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            padding: 10px;
            box-sizing: border-box;
            font-size: 20px;

            .item {
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .key {
                    word-break: keep-all;
                }

                .value {
                    text-align: center;
                    width: 100%;
                    color: #D37E6F;
                }

            }
        }

        .colums {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-between;
            font-size: 20px;

            .item {
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .key {
                    word-break: keep-all;
                }

                .value {
                    text-align: center;
                    width: 100%;
                    color: #D37E6F;
                }

            }
        }
    }
}

.leftBox {
    padding-top: 10px;

    .btnBox {
        display: flex;

        .btn {
            width: 50%;
            height: 32px;
            text-align: center;
            line-height: 32px;
            color: #666666;
            font-size: 14px;
            border-radius: 3px;
            position: relative;
            z-index: 1;
            transition: all .2s;

            &.cur {
                color: #fff;
            }

            img {
                position: absolute;
                width: 100%;
                height: 100%;
                z-index: -1;
                left: 0;
                top: 0;
            }

            &.btn1 {
                .darkBg {
                    transform: rotate(180deg);
                }
            }
        }
    }

    .entrustsBox {
        .entrusts {
            margin-top: 10px;

            .items {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: center;
                height: 20px;
                border: 1px solid rgba(227, 227, 227, 0.2);
                margin-right: 5px;
                border-radius: 3px;

                &:last-child {
                    margin-right: 0;
                }

                .icons {
                    width: 8px;
                    height: 6px;
                    margin-left: 5px;
                }

                .blue_text {
                    margin-left: 8px;
                }
            }

            .ganggan {
                position: fixed;
                top: 50%;
                transform: translateY(-50%);
                z-index: 200;

                width: 80%;
                min-height: 200px;
                background: #fff;
                border-radius: 5px;

                .con {
                    min-height: 100px;
                    padding: 0 15px;

                    .col {
                        height: 35px;
                        border: 1px solid #ededed;
                        border-radius: 2px;
                        text-align: center;
                        line-height: 35px;
                        margin-bottom: 10px;

                        &:hover {}
                    }
                }

                .btn {
                    font-size: 16px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    justify-items: center;
                    height: 40px;
                    line-height: 40px;

                    div {
                        text-align: center;
                        width: 50%;
                    }
                }
            }
        }

        .entrusts1 {
            display: flex;
            height: 27px;
            border: 1px solid rgba(227, 227, 227, 0.2);
            border-radius: 3px;
            align-items: center;
            padding-left: 15px;
            padding-right: 10px;
            color: #222222;
            font-size: 12px;

            .name {
                color: #a3a3a3;
                flex: 1;

                .inp {
                    // width: 100%;
                    height: 100%;
                    border: none;
                    outline: none;
                    padding-left: 10px;

                    &::placeholder {
                        color: #999999;
                    }

                    &:focus {
                        border: 1px solid #fbc400;
                    }
                }
            }

            .rightBorder {
                border: 1px solid #fbc400;
                color: #fbc400;
                border-radius: 3px;
                width: 43px;
                height: 27px;
                text-align: center;

                line-height: 27px;
                margin-right: -10px;
            }

            .rightBorder2 {
                border: 1px solid #fbc400;
                border-radius: 3px;
                width: 43px;
                height: 27px;
                text-align: center;
                line-height: 27px;
                margin-right: -10px;
                // z-index: 10;
            }

            .rightBorder3 {
                border: 1px solid #60AE68;
                border-radius: 3px;
                width: 43px;
                height: 27px;
                text-align: center;
                line-height: 27px;
                margin-right: -10px;
                // z-index: 10;
            }

            .rightBorder4 {
                border: 1px solid #FD614E;
                border-radius: 3px;
                width: 43px;
                height: 27px;
                text-align: center;
                line-height: 27px;
                margin-right: -10px;
                // z-index: 10;
            }
        }

        .pad_l_10 {
            padding-left: 10px !important;
        }
    }

    .handleBtn {
        width: 20px;
        height: 20px;
    }

    .balanceBox {
        padding-top: 5px;

        .items {
            margin-top: 5px;

            font-size: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    }

    .operatingBtn {
        .orange_bg {
            background-color: #F85D5A;
        }

        .items {
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 10px;
            position: relative;
            border-radius: 3px;
            font-size: 14px;

            .tips {
                position: absolute;
                font-size: 10px;
                color: rgba(255, 255, 255, 0.8);
                right: 10px;
            }
        }
    }
}

.contranctList {
    margin: 0 15px;
    padding: 0 15px;

    .titleBox {
        font-size: 12px;

        padding: 10px 0;
        margin: 0 -15px;
        padding: 15px;
        align-items: center;
    }

    .top {
        // border-bottom: 1px solid rgba(227, 227, 227, 0.2);

        .tabBar {
            font-size: 15px;

            display: flex;
            padding-top: 15px;

            span {
                margin-right: 50px;
                text-align: center;
                display: flex;
                flex-direction: column;
                justify-content: center;

                &:last-child {
                    margin-right: 0;
                }

                .bottomLine {
                    background: transparent;
                    width: 37px;
                    height: 2px;
                    display: inline-block;
                    margin: 10px auto 0;
                }

                &.active {
                    color: #0a76d4;
                    font-weight: bold;

                    .bottomLine {
                        background: #0a76d4;
                    }
                }
            }
        }

        .all {
            font-size: 12px;
            background: url(../../../../assets/detail/rightArrow.png) no-repeat right;
            background-size: 6px 10px;
            padding-right: 14px;
            display: flex;
            align-items: center;
        }
    }

    .listBox {
        padding-top: 10px;
    }
}

.v-enter-active,
.v-leave-active {
    transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
    opacity: 0;
}
</style>